import {createRouter, createWebHistory, RouteRecordRaw} from "vue-router";
import {getInfo} from "@/api/user/user";
import { userStore } from '@/store/modules/user';

const routes: RouteRecordRaw[] = [];

const modules: any = import.meta.glob("./modules/*.ts", {eager: true});
for (const path in modules) {
    routes.push(modules[path].default);
}

const router = createRouter({
    history: createWebHistory(),
    routes: routes,
    strict: false,
});

router.beforeEach((to, from, next) => {
    // 设置网页tab标题
    if (to.meta.title) {
        // @ts-ignore
        document.title = to.meta.title
    }
    // 获取用户信息
    const token = localStorage.getItem('token');
    if (token) {
        if (to.path === '/') {
            next('/wishList')
        } else {
            getInfo().then(({data, code}: any) => {
                if (code === 200) {
                    let store = userStore();
                    // 存储用户信息
                    store.setName(data.username);
                    store.setAvatar(data.avatar || ``);
                    store.setUserInfo(data);
                    store.setRole(data.role);
                    next();
                }
            });
        }
    } else {
        if (to.path === '/') {
            next('/wish')
        } else {
            next();
        }
    }
});

router.afterEach(() => {
});

export default router;
